import React, { Component } from 'react'
import {connect} from 'react-redux';
import {CarProductInter} from '../../../types/product.d'
import CarProduct from '../../../component/carProduct/carProduct'
import CarCss from './car.module.scss'
import { isTemplateElement } from '@babel/types';

interface Iprops{
    list:CarProductInter[],
    delProduct:(id:number) => void,
    checkAllFun:(checked:boolean) => void,
    checkAll:boolean
}

interface Istate{
    isShow:boolean,
    id:number
}

class Car extends Component<Iprops,Istate>{
    state = {
        isShow:false,
        id:-1
    }
    render() {
        let {list,checkAll} = this.props;
        let {isShow} = this.state;
        let total = list.reduce((prev:any,cur:CarProductInter) => {
            if(cur.checked){
                //如果为真
                return prev+cur.num*cur.price
            }else{
                return prev
            }
        },0)
        return (
            <div>
                <div>
                    {list && list.map(item => <CarProduct open={(id:number) => {
                        this.setState({
                            isShow:true,
                            id
                        })
                    }} key={item.id} item={item}></CarProduct>)}
                </div>
                <div>
                    全选：<input type="checkbox" checked={checkAll} onChange={(e) => {
                        this.props.checkAllFun(e.target.checked)
                    }} />  总价{total}
                </div>
                <div className={CarCss.model} style={{display:isShow?'block':'none'}}>
                    <h4>是否要删除？</h4>
                    <div>
                        <button onClick={this.close}>取消</button>
                        <button onClick={() => {
                            this.props.delProduct(this.state.id)
                            this.close()
                        }}>确定</button>
                    </div>
                </div>
            </div>
        )
    }

    close = () => {
        this.setState({
            isShow:false
        })
    }
}

let stateMapToProps = (state:any) => {
    return {
        list:state.list,
        checkAll:state.checkAll
    }
}

let dispatchMapToProps = (dispatch:any) => {
    return {
        delProduct(id:number){
            dispatch({type:'DEL_PRODUCT',id})
        },
        //全选
        checkAllFun(checked:boolean){
            dispatch({type:'CHEAK_ALL',checked})
        }
    }
}

export default connect(stateMapToProps,dispatchMapToProps)(Car);